<template>
    <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="用户账号" prop="account" label-width="120px">
          <el-input v-model="queryParams.account" placeholder="请输入用户账号" clearable style="width: 200px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="用户姓名" prop="name" label-width="120px">
          <el-input v-model="queryParams.name" placeholder="请输入用户姓名" clearable style="width: 200px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="用户角色" prop="roleID" label-width="120px">
        <el-select v-model="queryParams.roleID"  clearable placeholder="选择角色" style="width: 200px" @change="handleQuery">
            <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :data="userList" :max-height="tableHeight" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号" prop="account" align="center" width="120" />
      <el-table-column label="姓名" prop="name" align="center" width="300" />
      <el-table-column label="角色" align="center" prop="tenantDoMain" width="300">
        <template #default="scope">
          <span>{{ scope.row.role.name || '-' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="系统名称描述" prop="tenantDes" :show-overflow-tooltip="false" align="center" width="500" /> -->
      <el-table-column fixed="right" label="操作" align="center" min-width="160px" class-name="small-padding fixed-width">
        <template #default="scope">
         <!-- <div v-if="scope.row.roleID===1">内置角色</div> -->
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Key" @click="handleKey(scope.row)">重置密码</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="账号（手机号)" required prop="account" v-if="!form.id">
          <el-input v-model.trim="form.account" placeholder="请输入账号（手机号）" />
        </el-form-item>
        <el-form-item label="姓名" required prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="密码" required prop="passWord" v-if="!form.id">
          <el-input v-model.trim="form.passWord"  show-password type="password" placeholder="请输入密码（8 - 12 位字母和数字的组合）" >
          </el-input>
        </el-form-item>
        <el-form-item label="Email" prop="email">
          <el-input v-model.trim="form.email" placeholder="请输入Email" >
          </el-input>
        </el-form-item>
        <el-form-item label="头像" prop="photo">
          <ImageUpload v-model="form.photo" :limit="1" />
        </el-form-item>
        <el-form-item label="角色" prop="roleID" required>
          <el-select v-model="form.roleID"  placeholder="选择角色" size="large" style="width: 240px">
            <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Role">
import { GetTenantPageList,AddTenant ,EditTenant ,DelTenant} from "@/api/system/tenant";
import { useInfoStore } from '@/store/modules/info.js'
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");

const userInfo = useInfoStore();

const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const userList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);
const value = ref('')
const value2 = ref('')
const options = ref([])
const options2 = ref([])
const options3 = ref([])


const data = reactive({
 form: {
   id: null,
   account: null,//账号
   name: null,//姓名
   email: null,//邮箱
   passWord: null,//密码
   photo: null,//头像
   roleID: null,//角色ID
 },
 queryParams: {
   pageNo: 1,
   pageSize: 10,
   account: null,//账号
   name: null,//姓名
   roleID:null,//角色ID
   areaCode: null,//区域编码
 },
 rules: {
   account: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
   ],
   name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
   email: [
    { validator: (rule, value, callback) => { console.log(value); if (!value) { callback(); } else { const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; if (regex.test(value)) { callback(); } else { callback(new Error('请输入正确的邮箱地址')); } } }, trigger: 'blur' }
  ],
  passWord: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,12}$/, message: '密码必须为 8 - 12 位字母和数字的组合', trigger: 'blur' }
  ],
  roleID: [{ required: true, message: "请选择用户角色", trigger: "change" }],
 },
});

const { queryParams, form, rules } = toRefs(data);

async function getList() {
  loading.value = true;
   // 再查询用户列表
  proxy.API.GetUserPageList({
    ...queryParams.value,
    tenantID: userInfo.info.systemID,
  }).then(response => {
      userList.value = response.data.list;
      total.value = response.data.total;
  });
  loading.value = false;

}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
   clearTimeout(timer);
   timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
 queryParams.value.pageNo = 1;
 getList();
}

/** 重置按钮操作 */
function resetQuery() {
 dateRange.value = [];
 proxy.resetForm("queryRef");
 handleQuery();
}

/** 重置按钮操作 */
function handleKey(row) {
 proxy.$modal.confirm('是否确认重置账号"' + row.account + '"的密码?').then(function () {
  proxy.API.GetInitPassword({id:row.id}).then(response => {
     getList();
     proxy.$modal.confirm(`密码已重置：${response.data}`).then(function() {

      })
   });
 })
}
/** 删除按钮操作 */
function handleDelete(row) {
 proxy.$modal.confirm('是否确认删除账号"' + row.account + '"的数据项?').then(function () {
  proxy.API.DelUser({id:row.id}).then(response => {
     getList();
     proxy.$modal.msgSuccess("删除成功");
   });
 })
}

/** 导出按钮操作 */
function handleExport() {
 proxy.download("system/role/export", {
   ...queryParams.value,
 }, `role_${new Date().getTime()}.xlsx`);
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
 ids.value = selection.map(item => item.roleId);
 single.value = selection.length != 1;
 multiple.value = !selection.length;
}

/** 角色状态修改 */
function handleStatusChange(row) {
 let text = row.status === "0" ? "启用" : "停用";
 proxy.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?').then(function () {
   return changeRoleStatus(row.roleId, row.status);
 }).then(() => {
   proxy.$modal.msgSuccess(text + "成功");
 }).catch(function () {
   row.status = row.status === "0" ? "1" : "0";
 });
}

/** 更多操作 */
function handleCommand(command, row) {
 switch (command) {
   case "handleDataScope":
     handleDataScope(row);
     break;
   case "handleAuthUser":
     handleAuthUser(row);
     break;
   default:
     break;
 }
}

/** 分配用户 */
function handleAuthUser(row) {
 router.push("/system/role-auth/user/" + row.roleId);
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
 menuTreeselect().then(response => {
   menuOptions.value = response.data;
 });
}

/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
 // 目前被选中的部门节点
 let checkedKeys = deptRef.value.getCheckedKeys();
 // 半选中的部门节点
 let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
 checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
 return checkedKeys;
}

/** 重置新增的表单以及其他数据  */
function reset() {
 if (menuRef.value != undefined) {
   menuRef.value.setCheckedKeys([]);
 }
 form.value = {
   id: null,
   account: null,//账号
   name: null,//姓名
   email: null,//邮箱 
   passWord: null,//密码
   photo: null,//头像
   roleID: null,//角色ID
 };
 proxy.resetForm("roleRef");
}

/** 添加角色 */
function handleAdd() {
 reset();
 GetRoletList();
 open.value = true;
 title.value = "添加用户";
}

/** 修改角色 */
function handleUpdate(row) {
 reset();
 GetRoletList();
 Object.keys(form.value).forEach(key => {
   form.value[key] = row[key];
   if(form.value[key]==undefined){
     form.value[key]=null
   }
 });
 open.value = true;
 title.value = "修改用户";
}

/** 查询角色 */
function GetRoletList() {
 return proxy.API.GetRoletList({
  tenantID:userInfo.info.systemID,
 }).then(response => {
  if(response?.data.length>0){
    options2.value = response.data.map(item => {
     return { value: item.id, label: item.name }
   })
  }else{
    proxy.$modal.msgError("当前系统还没有角色，请先添加角色");
  }
 });
}

/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId) {
 return deptTreeSelect(roleId).then(response => {
   deptOptions.value = response.depts;
   return response;
 });
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
 if (type == "menu") {
   let treeList = menuOptions.value;
   for (let i = 0; i < treeList.length; i++) {
     menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
   }
 } else if (type == "dept") {
   let treeList = deptOptions.value;
   for (let i = 0; i < treeList.length; i++) {
     deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
   }
 }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
 if (type == "menu") {
   menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
 } else if (type == "dept") {
   deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
 }
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
 if (type == "menu") {
   form.value.menuCheckStrictly = value ? true : false;
 } else if (type == "dept") {
   form.value.deptCheckStrictly = value ? true : false;
 }
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
 // 目前被选中的菜单节点
 let checkedKeys = menuRef.value.getCheckedKeys();
 // 半选中的菜单节点
 let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
 checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
 return checkedKeys;
}

// 处理值变化的方法
const handleChange = (value) => {
 if (Number.isInteger(value)) {
   if (value < 0) {
     form.value.tenantOrders = 0;
   } else if (value > 9) {
     form.value.tenantOrders = 9;
   }
 } else {
   // 如果不是整数，恢复到上一个有效值
   form.value.tenantOrders = Math.round(form.value.tenantOrders);
 }
}

/** 提交按钮 */
function submitForm() {
 proxy.$refs["roleRef"].validate(valid => {
   if (valid) {
    console.log(form.value);
    if(form.value.id){
       form.value.account = null;
       form.value.passWord = null;
       proxy.API.UpdateUser({...form.value,systemID:value.value}).then(response => {
         proxy.$modal.msgSuccess("修改成功");
         open.value = false;
         getList();
       });
    }else{
       proxy.API.AddUser({...form.value,systemID:value.value}).then(response => {
         proxy.$modal.msgSuccess("新增成功");
         open.value = false;
         getList();
       });
    }
   }
 });
}
// 复制
async function copy(text){
 console.log(text);
 try {
   await navigator.clipboard.writeText(text);
   proxy.$modal.msgSuccess('复制成功');
 } catch (err) {
   console.log(err);
   
 }
}

/** 取消按钮 */
function cancel() {
 open.value = false;
 reset();
}

/** 选择角色权限范围触发 */
function dataScopeSelectChange(value) {
 if (value !== "2") {
   deptRef.value.setCheckedKeys([]);
 }
}

/** 提交按钮（数据权限） */
function submitDataScope() {
 if (form.value.roleId != undefined) {
   form.value.deptIds = getDeptAllCheckedKeys();
   dataScope(form.value).then(response => {
     proxy.$modal.msgSuccess("修改成功");
     openDataScope.value = false;
     getList();
   });
 }
}

/** 取消按钮（数据权限）*/
function cancelDataScope() {
 openDataScope.value = false;
 reset();
}
getList();
</script>
<style lang="scss" scoped>
.select{
  ::v-deep(.el-select__icon){
   color: #409EFF;
 }
}
</style>